package com.cropdoctor.common;

import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.NestedServletException;

import java.sql.SQLIntegrityConstraintViolationException;

//统一异常处理类
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);  // 创建日志记录器

    /*自定义异常处理方法*/
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception exception){
        logger.error("全局异常捕获");
        System.out.println(exception.getMessage());
        return Result.error(exception.getMessage());
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result<String> sqlExceptionHandler(Exception exception){
        logger.error("sql异常捕获");
        System.out.println(exception.getMessage());
        if(exception.getCause().getMessage().startsWith("Data")){
            return Result.error("输入过长,请删除一些不必要信息哦");
        }
        return Result.error(exception.getMessage());
    }

    /*自定义异常处理方法*/
    @ExceptionHandler(CustomException.class)
    public Result<String> exceptionHandler(CustomException customException){
        logger.error("自定义异常捕获");
        System.out.println(customException.getMessage());
        return Result.error(customException.getMessage());
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        logger.info(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return  Result.error(msg);
        }
        return Result.error("未知错误");
    }

    @ExceptionHandler(NestedServletException.class)
    public Result<String> exceptionHandler(NestedServletException e){
        logger.info(e.getMessage());
        if (e.getCause() instanceof OutOfMemoryError) {
            return  Result.error("上传文件过大!");
        }
        return Result.error("未知错误");
    }

}
